import Vue from "vue";
import VueRouter from "vue-router";

const originalPush = VueRouter.prototype.push;

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(console.warn);
};

VueRouter.prototype.replace = function push(location) {
  return originalPush.call(this, location).catch(console.warn);
};

Vue.use(VueRouter);

const defaultTitle = "默认标题";

const routes = [
  {
    path: "/",
    redirect: { name: "Home", keep: true },
  },
  // 角色列表
  {
    path: "/home",
    name: "Home",
    component: () => import("../pages/home/"),
  },
];

const router = new VueRouter({
  mode: "hash",
  routes,
});

// 路由跳转后 设置页面标题
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title + " - " + defaultTitle;
  } else document.title = defaultTitle;

  next();
});

// 路由跳转前置操作
router.afterEach(() => {});

// 执行返回操作
router.back = function () {
  window.routerback = true;
  history.go(-1);
};

const _push = router.push;
// 执行跳转操作
router.push = function (location) {
  window.routerback = false; // 标记路由当前向前跳转
  saveScrollTop(this.currentRoute.fullPath); // 保存滚动条位置
  _push.call(this, location);
};

const _replace = router.replace;
// 执行清除堆栈跳转操作
router.replace = function (location) {
  window.routerback = false; // 标记路由当前向前跳转
  saveScrollTop(this.currentRoute.fullPath); // 保存滚动条位置
  _replace.call(this, location);
};

/**
 * 保存滚动条位置
 * @param {*} path
 */
function saveScrollTop(path) {
  window.pathScrollTop = window.pathScrollTop || {};
  window.pathScrollTop[path] = window.scrollY;
}

export default router;
